<template>
	<view class="appointment-detail-container">
		<!-- 顶部信息卡片 -->
		<view class="info-card" :class="{'card-animation': showCardAnimation}">
			<view class="student-info">
				<image class="avatar" src="/static/aver1.jpg" mode="aspectFill"></image>
				<view class="info-text">
					<text class="name">{{detail.studentName}}</text>
					<text class="grade">{{detail.studentGrade}}</text>
				</view>
			</view>
			<view class="divider">
				</div>
				<view class="appointment-info">
					<!-- <view class="info-item">
						<uni-icons type="calendar" size="18" color="#666"></uni-icons>
						<text>{{detail.appointmentTime}}</text>
					</view>
					<view class="info-item">
						<uni-icons type="phone" size="18" color="#666"></uni-icons>
						<text>{{detail.studentPhone}}</text>
					</view> -->
					<view class="info-item">
						<uni-icons type="person" size="18" color="#666"></uni-icons>
						<text>{{detail.teacherName}}</text>
					</view>
				</view>
			</view>
			<view class="content-section" :class="{'content-animation': showContentAnimation}">
				<view class="section-title">
					<text>预约时间</text>
				</view>
				<view class="content-box">
					<text>{{detail.appointmentTime}}</text>
				</view>
			</view>
			<!-- 主要内容区域 -->
			<view class="content-section" :class="{'content-animation': showContentAnimation}">
				<view class="section-title">
					<text>预约内容</text>
				</view>
				<view class="content-box">
					<text>{{detail.appointmentContent}}</text>
				</view>
			</view>

			<!-- 状态和操作区域 -->
			<view class="status-section" :class="{'status-animation': showStatusAnimation}">
				<view class="status-display">
					<view class="status-badge" :class="statusClass">
						<text>{{statusText}}</text>
					</view>
					<text class="create-time" v-if="detail.isFinish === 0">请至少上传1张辅导照片</text>
				</view>

				<!-- 上传照片区域（未辅导状态显示） -->
				<view v-if="detail.isFinish === 0" class="upload-section">
					<view class="section-title">
						<!-- <text>上传辅导照片</text> -->
						<button class="upload-btn" @click="chooseImage">上传辅导照片</button>
					</view>
					<view class="upload-container">

						<view class="image-preview">
							<view class="image-item" v-for="(image, index) in images" :key="index">
								<image :src="image.localPath" class="image-thumbnail" mode="aspectFill" />
								<view class="image-info">
									<view class="progress-bar" v-if="image.status === 'uploading'">
										<view class="progress" :style="{ width: image.progress + '%' }"></view>
									</view>
									<text class="upload-status">
										{{
						          image.status === 'done' ? '已完成' : 
						          image.status === 'uploading' ? '上传中...' + image.progress + '%' : 
						          '等待上传'
						        }}
									</text>
								</view>
								<button class="remove-btn" @click="removeImage(index)">删除</button>
							</view>
						</view>
					</view>

					<view class="evaluation-input">
						<view class="section-title">
							<text>辅导评价</text>
						</view>
						<textarea maxlength="300" v-model="teacherEvaluation" placeholder="请输入本次辅导的评价..."
							class="evaluation-textarea"></textarea>
					</view>
				</view>

				<!-- 已上传照片展示区域（已完成状态显示） -->
				<view v-if="detail.isFinish === 1 || detail.isFinish === 2" class="uploaded-images">
					<view class="section-title">
						<text>辅导照片</text>
					</view>
					<view class="images-grid" v-if="uploadedImages.length > 0">
						<image v-for="(image, index) in uploadedImages" :key="index" :src="image" class="uploaded-image"
							mode="aspectFill" @click="previewImage(index)"></image>
					</view>
					<view v-else class="no-images">
						<text>暂无辅导照片</text>
					</view>
					<view class="evaluation-section" v-if="detail.teacherComponent">
						<view class="evaluation-title">
							<text>老师评价</text>
						</view>
						<view class="evaluation-content">
							<text>{{detail.teacherComponent}}</text>
						</view>
					</view>
				</view>

				<!-- 评价区域 -->
				<template v-if="detail.isFinish === 2">
					<view class="evaluation-section" v-if="detail.component">
						<view class="evaluation-title">
							<text>家长评价</text>
						</view>
						<view class="evaluation-content">
							<text>{{detail.component}}</text>
						</view>
					</view>

					<!-- <view class="evaluation-section" v-if="detail.teacherComponent">
						<view class="evaluation-title">
							<text>老师评价</text>
						</view>
						<view class="evaluation-content">
							<text>{{detail.teacherComponent}}</text>
						</view>
					</view> -->
				</template>
			</view>

			<!-- 底部操作按钮 -->
			<view class="action-buttons" v-if="detail.isFinish === 0">
				<button class="btn cancel-btn" @click="handleCancel">取消预约</button>
				<button class="btn confirm-btn" :disabled="isUploading" @click="handleConfirm">
					{{ isUploading ? '正在提交...' : '确认完成辅导' }}
				</button>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		globalVariable
	} from '../../configMy.js';
	export default {
		data() {
			return {
				detail: {},
				showCardAnimation: false,
				showContentAnimation: false,
				showStatusAnimation: false,
				images: [], // 存储待上传的图片信息
				uploadedImages: [], // 存储已上传的图片URL
				teacherEvaluation: "", // 老师评价内容
				isUploading: false // 是否正在上传
			};
		},
		computed: {
			statusText() {
				const statusMap = {
					0: '未辅导',
					1: '已辅导(待审核)',
					2: '已完成'
				};
				return statusMap[this.detail.isFinish] || '';
			},
			statusClass() {
				return `status-${this.detail.isFinish}`;
			}
		},
		onLoad(options) {
			let detail = JSON.parse(options.detail);
			this.detail = detail;
			// 模拟数据加载
			setTimeout(() => {
				this.showCardAnimation = true;
			}, 100);

			setTimeout(() => {
				this.showContentAnimation = true;
			}, 200);

			setTimeout(() => {
				this.showStatusAnimation = true;
			}, 200);

			// 模拟获取已上传的图片
			if (this.detail.isFinish === 1 || this.detail.isFinish === 2) {
				this.getUploadedImages();
			}
		},
		methods: {
			async compressImage(filePath, quality = 0.7, maxWidth = 1024) {
				return new Promise((resolve) => {
					uni.getImageInfo({
						src: filePath,
						success: (imageInfo) => {
							const canvas = document.createElement('canvas');
							const ctx = canvas.getContext('2d');

							// 计算压缩后的尺寸
							let width = imageInfo.width;
							let height = imageInfo.height;
							if (width > maxWidth) {
								height = (maxWidth / width) * height;
								width = maxWidth;
							}

							canvas.width = width;
							canvas.height = height;

							const img = new Image();
							img.onload = () => {
								ctx.drawImage(img, 0, 0, width, height);
								canvas.toBlob((blob) => {
									// 将Blob转换为临时文件路径
									const reader = new FileReader();
									reader.onload = () => {
										resolve({
											path: reader.result,
											width,
											height,
											size: blob.size
										});
									};
									reader.readAsDataURL(blob);
								}, 'image/jpeg', quality);
							};
							img.src = filePath;
						},
						fail: () => {
							// 压缩失败则返回原图
							resolve({
								path: filePath
							});
						}
					});
				});
			},
			chooseImage() {
				uni.chooseImage({
					count: 5,
					sourceType: ['album', 'camera'],
					success: async (res) => {
						// 显示压缩进度
						uni.showLoading({
							title: '正在压缩图片...',
							mask: true
						});

						// 压缩所有选择的图片
						for (const tempPath of res.tempFilePaths) {
							const compressed = await this.compressImage(tempPath);
							this.images.push({
								localPath: compressed.path,
								serverPath: null,
								progress: 0,
								status: 'waiting'
							});
						}

						uni.hideLoading();
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},
			async uploadImages() {
				if (this.images.length === 0) {
					return Promise.resolve([]);
				}

				// 更新所有图片状态为上传中
				this.images = this.images.map(img => ({
					...img,
					status: img.progress > 0 ? 'uploading' : 'waiting'
				}));

				this.isUploading = true;
				uni.showLoading({
					title: '上传图片中...',
					mask: true
				});

				try {
					const uploadPromises = this.images.map((image, index) => {
						if (image.status === 'done') {
							return Promise.resolve(image.serverPath);
						}
						return this.uploadImage(image.localPath, index);
					});

					const results = await Promise.all(uploadPromises);
					return results.filter(url => url); // 过滤掉可能为null的结果
				} catch (error) {
					console.error('图片上传失败:', error);
					throw error;
				} finally {
					uni.hideLoading();
					this.isUploading = false;
				}
			},

			uploadImage(localPath, index) {
				return new Promise(async (resolve, reject) => {
					try {
						// 先压缩再上传
						const compressed = await this.compressImage(localPath);

						// 更新状态为上传中
						this.$set(this.images[index], 'status', 'uploading');

						const uploadTask = uni.uploadFile({
							url: globalVariable + '/uploadAppPhoto',
							filePath: compressed.path,
							name: 'file',
							formData: {
								appointmentId: this.detail.id
							},
							success: (res) => {
								if (res.statusCode === 200) {
									const data = JSON.parse(res.data);
									// 更新图片状态和服务器路径
									this.$set(this.images[index], 'serverPath', data.url);
									this.$set(this.images[index], 'status', 'done');
									resolve(data.url);
								} else {
									reject(new Error('上传失败'));
								}
							},
							fail: (err) => {
								reject(err);
							}
						});

						uploadTask.onProgressUpdate((progress) => {
							this.$set(this.images[index], 'progress', progress.progress);
						});
					} catch (error) {
						reject(error);
					}
				});
			},

			// // 上传单张图片
			// uploadImage(localPath, index) {
			// 	return new Promise((resolve, reject) => {
			// 		// 更新状态为上传中
			// 		this.$set(this.images[index], 'status', 'uploading');

			// 		const uploadTask = uni.uploadFile({
			// 			url: globalVariable + '/uploadAppPhoto',
			// 			filePath: localPath,
			// 			name: 'file',
			// 			formData: {
			// 				appointmentId: this.detail.id
			// 			},
			// 			success: (res) => {
			// 				if (res.statusCode === 200) {
			// 					const data = JSON.parse(res.data);
			// 					// 更新图片状态和服务器路径
			// 					this.$set(this.images[index], 'serverPath', data.url);
			// 					this.$set(this.images[index], 'status', 'done');
			// 					resolve(data.url);
			// 				} else {
			// 					reject(new Error('上传失败'));
			// 				}
			// 			},
			// 			fail: (err) => {
			// 				reject(err);
			// 			}
			// 		});

			// 		uploadTask.onProgressUpdate((progress) => {
			// 			this.$set(this.images[index], 'progress', progress.progress);
			// 		});
			// 	});
			// },

			async handleConfirm() {
				if (!this.teacherEvaluation) {
					uni.showToast({
						title: '请填写辅导评价',
						icon: 'none'
					});
					return;
				}

				uni.showModal({
					title: '提示',
					content: '确定要确认完成本次辅导吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								// 先上传图片
								const imageUrls = await this.uploadImages();

								// 然后提交评价和图片
								await this.confirmAppointment(imageUrls);

								uni.showToast({
									title: '提交成功',
									icon: 'success'
								});

								// 刷新页面数据
								this.detail.isFinish = 1;
								this.detail.teacherComponent = this.teacherEvaluation;
								await this.getUploadedImages();

							} catch (error) {
								uni.showToast({
									title: '提交失败: ' + error.message,
									icon: 'none'
								});
							}
						}
					}
				});
			},
			// 获取已上传的图片
			async getUploadedImages() {
				try {
					const res = await uni.request({
						url: globalVariable + '/getAppointmentImage?appointmentId=' + this.detail.id,
						method: 'GET',
					});
					let images = (res.data.data);

					console.log(images)
					this.uploadedImages = images.map(item => {
						return globalVariable + '/get2/' + item.averPath;

					});
				} catch (error) {
					console.error('获取图片失败:', error);
				}
			},



			// 删除图片
			removeImage(index) {
				this.images.splice(index, 1);
			},

			// 预览图片
			previewImage(index) {
				uni.previewImage({
					current: this.uploadedImages[index],
					urls: this.uploadedImages
				});
			},



			// 取消预约
			handleCancel() {
				uni.showModal({
					title: '提示',
					content: '确定要取消本次预约吗？',
					success: (res) => {
						if (res.confirm) {
							this.cancelAppointment();
						}
					}
				});
			},


			// 调用取消预约接口
			async cancelAppointment() {
				try {
					// await uni.request({
					//   url: '/api/appointment/cancel',
					//   method: 'POST',
					//   data: { id: this.detail.id }
					// });

					uni.showToast({
						title: '取消成功',
						icon: 'success'
					});

					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} catch (error) {
					uni.showToast({
						title: '取消失败',
						icon: 'none'
					});
				}
			},

			// 调用确认预约接口
			async confirmAppointment() {
				try {
					await uni.request({
						url: globalVariable + '/changeMyComponent?id=' + this.detail.id + "&comment=" + this
							.teacherEvaluation,
						method: 'POST',
					});
					this.detail.isFinish = 1;
					this.detail.teacherComponent = this.teacherEvaluation;


				} catch (error) {
					throw error;
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	.progress-bar {
		width: 100%;
		height: 8rpx;
		background-color: #e0e0e0;
		border-radius: 4rpx;
		overflow: hidden;
		margin-bottom: 10rpx;

		.progress {
			height: 100%;
			background: linear-gradient(90deg, #4a8cff, #6a5acd);
			transition: width 0.3s ease;
		}
	}

	.upload-status {
		font-size: 24rpx;
		color: #666;

		&.waiting {
			color: #999;
		}

		&.uploading {
			color: #4a8cff;
		}

		&.done {
			color: #4caf50;
		}
	}

	.appointment-detail-container {
		// padding: 20rpx;
		background-color: #f5f7fa;
		// min-height: 100vh;

		.info-card {
			background: linear-gradient(135deg, #ffffff, #f8f9fa);
			border-radius: 16rpx;
			padding: 30rpx;
			box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);
			margin-bottom: 30rpx;
			transform: translateY(50rpx);
			opacity: 0;
			transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1);

			&.card-animation {
				transform: translateY(0);
				opacity: 1;
			}

			.student-info {
				display: flex;
				align-items: center;
				margin-bottom: 30rpx;

				.avatar {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					margin-right: 20rpx;
					border: 4rpx solid rgba(255, 255, 255, 0.8);
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
				}

				.info-text {
					display: flex;
					flex-direction: column;

					.name {
						font-size: 36rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 10rpx;
					}

					.grade {
						font-size: 28rpx;
						color: #666;
					}
				}
			}

			.divider {

				// background: linear-gradient(90deg, transparent, #e0e0e0, transparent);
				margin: 20rpx 0;
			}

			.appointment-info {
				.info-item {
					display: flex;
					align-items: center;
					margin-bottom: 20rpx;
					font-size: 28rpx;
					color: #666;

					uni-icons {
						margin-right: 15rpx;
					}
				}
			}
		}

		.content-section {
			margin-top: 30rpx;
			background-color: #fff;
			border-radius: 16rpx;
			padding: 30rpx;
			box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);
			margin-bottom: 30rpx;
			transform: translateY(50rpx);
			opacity: 0;
			transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1) 0.2s;

			&.content-animation {
				transform: translateY(0);
				opacity: 1;
			}

			.section-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 20rpx;
				position: relative;
				padding-left: 20rpx;

				&::before {
					content: '';
					position: absolute;
					left: 0;
					top: 50%;
					transform: translateY(-50%);
					width: 8rpx;
					height: 32rpx;
					background-color: #4a8cff;
					border-radius: 4rpx;
				}
			}

			.content-box {
				background-color: #f8f9fa;
				padding: 20rpx;
				border-radius: 12rpx;
				font-size: 28rpx;
				color: #555;
				line-height: 1.6;
			}
		}

		.status-section {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 30rpx;
			box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);
			transform: translateY(50rpx);
			opacity: 0;
			transition: all 0.6s cubic-bezier(0.23, 1, 0.32, 1) 0.4s;

			&.status-animation {
				transform: translateY(0);
				opacity: 1;
			}

			.status-display {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 30rpx;

				.status-badge {
					padding: 10rpx 20rpx;
					border-radius: 50rpx;
					font-size: 26rpx;
					font-weight: bold;

					&.status-0 {
						background-color: #ffecb3;
						color: #ff9800;
					}

					&.status-1 {
						background-color: #b3e0ff;
						color: #2196f3;
					}

					&.status-2 {
						background-color: #c8e6c9;
						color: #4caf50;
					}
				}

				.create-time {
					font-size: 24rpx;
					color: #999;
				}
			}

			/* 上传照片区域 */
			.upload-section {
				margin-top: 30rpx;

				.upload-container {
					background-color: #f8f9fa;
					padding: 20rpx;
					border-radius: 12rpx;
				}

				.upload-btn {
					background-color: #4a8cff;
					color: white;
					padding: 15rpx 30rpx;
					border-radius: 40rpx;
					font-size: 28rpx;
					margin-bottom: 20rpx;
				}

				.image-preview {
					display: flex;
					flex-direction: column;
					gap: 20rpx;
				}

				.image-item {
					display: flex;
					align-items: center;
					background: white;
					padding: 20rpx;
					border-radius: 12rpx;
					box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
					position: relative;
				}

				.image-thumbnail {
					width: 120rpx;
					height: 120rpx;
					border-radius: 8rpx;
					object-fit: cover;
				}

				.image-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: center;
					margin-left: 20rpx;
				}

				.progress-bar {
					width: 100%;
					height: 8rpx;
					background-color: #e0e0e0;
					border-radius: 4rpx;
					overflow: hidden;
					margin-bottom: 10rpx;
				}

				.progress {
					height: 100%;
					background-color: #4a8cff;
					transition: width 0.3s ease;
				}

				.upload-status {
					font-size: 24rpx;
					color: #666;
				}

				.remove-btn {
					position: absolute;
					right: 20rpx;
					bottom: 20rpx;
					background-color: rgba(255, 59, 48, 0.8);
					color: white;
					padding: 8rpx 16rpx;
					border-radius: 6rpx;
					font-size: 24rpx;
				}

				.evaluation-input {
					margin-top: 30rpx;

					.evaluation-textarea {
						box-sizing: border-box;
						width: 100%;
						height: 300rpx;
						background-color: #f8f9fa;
						border-radius: 12rpx;
						padding: 20rpx;
						font-size: 28rpx;
						color: #555;
						line-height: 1.6;
					}
				}
			}

			/* 已上传照片展示区域 */
			.uploaded-images {
				margin-top: 30rpx;

				.images-grid {
					display: grid;
					grid-template-columns: repeat(3, 1fr);
					gap: 10rpx;
					margin-top: 20rpx;
				}

				.uploaded-image {
					width: 100%;
					height: 220rpx;
					border-radius: 8rpx;
				}

				.no-images {
					text-align: center;
					padding: 40rpx 0;
					color: #999;
					font-size: 28rpx;
				}
			}

			.evaluation-section {
				margin-top: 30rpx;

				.evaluation-title {
					font-size: 30rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 20rpx;
					display: flex;
					align-items: center;

					&::before {
						content: '';
						display: inline-block;
						width: 8rpx;
						height: 30rpx;
						background-color: #4a8cff;
						margin-right: 15rpx;
						border-radius: 4rpx;
					}
				}

				.evaluation-content {
					background-color: #f8f9fa;
					padding: 20rpx;
					border-radius: 12rpx;
					font-size: 28rpx;
					color: #555;
					line-height: 1.6;
				}
			}
		}

		.action-buttons {
			display: flex;
			justify-content: space-between;
			margin-top: 40rpx;
			padding: 0 20rpx;

			.btn {
				flex: 1;
				height: 90rpx;
				line-height: 90rpx;
				border-radius: 45rpx;
				font-size: 32rpx;
				font-weight: bold;
				margin: 0 15rpx;
				transition: all 0.3s;

				&:active {
					transform: scale(0.95);
				}

				&[disabled] {
					opacity: 0.7;
				}
			}

			.cancel-btn {
				background-color: #fff;
				color: #ff5252;
				border: 2rpx solid #ff5252;

				&:active {
					background-color: #ffeeee;
				}
			}

			.confirm-btn {
				background: linear-gradient(90deg, #4a8cff, #6a5acd);
				color: #fff;
				box-shadow: 0 8rpx 20rpx rgba(74, 140, 255, 0.3);

				&:active {
					box-shadow: 0 4rpx 10rpx rgba(74, 140, 255, 0.3);
				}

				&[disabled] {
					background: linear-gradient(90deg, #cccccc, #999999);
					box-shadow: none;
				}
			}
		}
	}
</style>